﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using MySql.Data.MySqlClient;

namespace iLikeLite
{
    class Search
    {
        public string curHistogram;

        public ArrayList GetSearchResultIds(string query)
        {
            ArrayList resultIds = new ArrayList();
            curHistogram = "";

            MySqlConnection conn = new MySqlConnection(Properties.Settings.Default.mydbConnectionString);
            conn.Open();

            MySqlCommand cmd = new MySqlCommand("SELECT histogram FROM keywords WHERE keyword = ?k", conn);
            cmd.Parameters.AddWithValue("?k", query.ToLower());
            MySqlDataReader reader = cmd.ExecuteReader();

            if (reader.Read())
            {
                ArrayList results = new ArrayList();
                curHistogram = reader.GetString("histogram");
                double[] keywordHistogram = DecodeHistogram(curHistogram);
                reader.Close();

                cmd = new MySqlCommand("SELECT id, histogram FROM images", conn);
                reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    results.Add(new HistoDiff(reader.GetInt32("id"), GetHistogramDiff(keywordHistogram, DecodeHistogram(reader.GetString("histogram")))));
                }

                results.Sort();

                for (int i = 0; i < results.Count; ++i)
                {
                    resultIds.Add(((HistoDiff)results[i]).ID);
                }
            }

            return resultIds;
        }

        private double[] DecodeHistogram(string histogramStr)
        {
            string[] histoStrs = histogramStr.Split(',');
            double[] histogram = new double[histoStrs.Length];
            for (int i = 0; i < histogram.Length; ++i)
            {
                histogram[i] = Convert.ToDouble(histoStrs[i]);
            }
            return histogram;
        }

        private double GetHistogramDiff(double[] histo1, double[] histo2)
        {
            double diff = 0;
            if (histo1.Length == histo2.Length)
            {
                for (int i = 0; i < histo1.Length; ++i)
                {
                    diff += Math.Abs(histo1[i] - histo2[i]);
                }
            }
            return diff;
        }
    }

    class HistoDiff : IComparable
    {
        public int ID;
        public double Difference;

        public HistoDiff(int histoId, double diff)
        {
            this.ID = histoId;
            this.Difference = diff;
        }

        #region IComparable Members

        public int CompareTo(object obj)
        {
            return Difference.CompareTo(((HistoDiff)obj).Difference);
        }

        #endregion
    }
}
